package cn.bone.search.dao;

import cn.bone.search.bean.NewsDo;
import io.searchbox.client.JestClient;
import io.searchbox.core.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by superbone on 2017/3/21.
 */
@Repository
public class SearchDao {

    @Resource
    private JestClient jestClient;
    private Logger logger = LoggerFactory.getLogger("elasticsearch索引");

    private String indexName = "superbone";
    private String typeName = "news";

    public String indexOne(NewsDo obj){

        String result = null;
        Index index = new Index.Builder(obj)
                .index(indexName)
                .type(typeName)
                .build();
        try {
            DocumentResult documentResult = jestClient.execute(index);
            if(documentResult.isSucceeded()){
                result = documentResult.getId();
            }else{
                logger.info("添加索引失败:/"+indexName+"/"+typeName);
                logger.info(documentResult.getErrorMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean indexList(List<NewsDo> list){

        boolean result = false;
        Bulk.Builder bulk = new Bulk.Builder()
                .defaultIndex(indexName)
                .defaultType(typeName);
        for(NewsDo obj : list){
            Index index = new Index.Builder(obj).build();
            bulk.addAction(index);
        }
        try {
            BulkResult bulkResult = jestClient.execute(bulk.build());
            if(bulkResult.isSucceeded()){
                result = true;
            }else{
                logger.info("添加索引失败:/"+indexName+"/"+typeName);
                logger.info(bulkResult.getErrorMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public List<NewsDo> query(String keyword,Integer start,Integer num){
        final List<NewsDo> newsList = new ArrayList<>();
        if(StringUtils.isEmpty(keyword)){
            return newsList;
        }
        if(start==null){
            start = 0;
        }
        if(num==null){
            num = 10;
        }
        /*
            将查询语句的字符串传入Search.Builder中
            {
                "query":{
                    "multi_match":{
                        "query":"阳新",
                        "fields": ["title","content"]
                    }
                },
                "from": 0,
                "size": 20
            }
        */
        String query = "{\"query\":{" +
                "\"multi_match\":{" +
                "\"query\":\""+ keyword +"\"," +
                "\"fields\":[\"title\",\"content\"]" +
                "}" +
                "}," +
                "\"from\":" + start + "," +
                "\"size\":" + num +
                "}";
        logger.info(query);
        Search search = new Search.Builder(query)
                .addIndex(indexName)
                .addType(typeName)
                .build();
        try {
            SearchResult searchResult = jestClient.execute(search);
            if(searchResult.isSucceeded()){
                Integer total = searchResult.getTotal();
                List<SearchResult.Hit<NewsDo, Void>> hits = searchResult.getHits(NewsDo.class);
                logger.info("一共查询到"+total+"条记录,当前获取"+hits.size()+"条");
                Iterator<SearchResult.Hit<NewsDo, Void>> iterator = hits.iterator();
                while(iterator.hasNext()){
                    NewsDo source = iterator.next().source;
                    newsList.add(source);
                }
            }else{
                logger.info("查询不成功:"+searchResult.getErrorMessage());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return newsList;
    }

    public boolean delete(String id){
        boolean result = false;
        Delete delete = new Delete.Builder(id)
                .index(indexName)
                .type(typeName)
                .build();
        try {
            DocumentResult deleteResult = jestClient.execute(delete);
            result = deleteResult.isSucceeded();
            if(deleteResult.isSucceeded()){
                logger.info("删除成功:"+deleteResult.getId());
            }else{
                logger.info("删除失败:"+deleteResult.getId());
                logger.info(deleteResult.getErrorMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
